import csv
import os
from wordNoteApp import models
def csv_change(tableDict,filename):
    if filename:
        fileName=os.path.join("static/downloads/",filename+".csv")
    else:
        fileName="static/downloads/default.csv"
    #filedir=os.path.join(settings.BASE_DIR,"/downloads/test.csv")
    with open(fileName,"w") as csvfile:
        fieldname=["id","word","explanation","remark"]
        dictReader=csv.DictWriter(csvfile,fieldnames=fieldname)
        dictReader.writeheader()
        for row in tableDict:
            dictReader.writerow(row)

def csv_update(file):
    models.wordBook.objects.all().delete()
    with open(os.path.join("static/downloads/",file),"r",newline='') as csvfile:
        csvobj=csv.DictReader(csvfile)
        for row in csvobj:
            if row["id"]:
                models.wordBook.objects.create(id=row["id"],word=row["word"],
                                               explanation=row["explanation"],
                                               remark=row["remark"])